package offer.offer04;

import java.math.BigInteger;

/**
 * 注意审题, 遇到第一个非空字符就收进来
 */
public class Solution67_2 {
    public int strToInt(String str) {
        StringBuilder strBuilder = new StringBuilder(str);
        StringBuilder resultBuilder = new StringBuilder("");
        int resultInt = 0;
        for(int i = 0; i < strBuilder.length(); i++){
            if(strBuilder.charAt(i) == '+' || strBuilder.charAt(i) == '-'||Character.isDigit(strBuilder.charAt(i))){
                resultBuilder.append(strBuilder.charAt(i));//第一个是标点或者数字
                for(int j = i + 1; j < strBuilder.length(); j++){
                    //Character c = Character.valueOf(strBuilder.charAt(j));这个是Character类的创建方式
                    //把往后遇到的所有数字都存进去, 遇到第一个不是数字的就停止
                    if(Character.isDigit(strBuilder.charAt(j))) resultBuilder.append(strBuilder.charAt(j));
                    else break;
                }
                break;//只需要执行一次;
            }
        }
        System.out.println(resultBuilder);
        int flag = 1;
        if(resultBuilder.charAt(0) == '+' || resultBuilder.charAt(0) == '-'){
            flag = resultBuilder.charAt(0) == '+'? 1 : -1;
            //删除第一位
            resultBuilder.delete(0, 1);
        }
        if(resultBuilder.length() != 0){
            BigInteger resultBig = new BigInteger(resultBuilder.toString());
            System.out.println("结果的数字部分为: " + resultBig);
            if(flag == 1 && resultBig.compareTo(new BigInteger("" + Integer.MAX_VALUE)) == 1){
                resultBig = new BigInteger("" + Integer.MAX_VALUE);
            }else {
                if(flag == -1 && resultBig.compareTo(new BigInteger("2147483648")) == 1){
                    resultBig = new BigInteger("" + Math.abs(Integer.MIN_VALUE));
                }
            }
            resultInt = resultBig.intValue();
        }

        return resultInt*flag;
    }
    public static void main(String[] args) {
        String input = "sdfygfg sdfr -434364889765542346 5437984573468756 876 097096";
        System.out.println("输出结果为: " + new Solution67_2().strToInt(input));
    }
}
